import java.util.Stack;

public class Solution735 {
    public int[] asteroidCollision(int[] asteroids) {
        int n = asteroids.length;
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < n; i++) {
            if (stack.isEmpty() || stack.peek() < 0 || asteroids[i] > 0) {
                stack.push(asteroids[i]);
            } else {//15 10  -15
                while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < -asteroids[i]) {
                    stack.pop();
                }
                //活下来了，还有最后一关
                if (!stack.isEmpty() && stack.peek() == -asteroids[i]) {
                    stack.pop();
                } else if (stack.isEmpty() || stack.peek() < 0) {
                    stack.push(asteroids[i]);
                }
            }

        }

        int[] res = new int[stack.size()];
        for (int i = res.length - 1; i >= 0; i--) {
            res[i] = stack.pop();
        }
        return res;
    }

    public static void main(String[] args) {
        int[] a = {-2, -2, 1, -2};
        int[] ints = new Solution735().asteroidCollision(a);
        for (int i :
                ints) {
            System.out.println(i);
        }
    }
}
